import processing.serial.*;

Serial myPort;  // Serial port object
float[] voltages = new float[3]; // Array to store sensor voltages
boolean[] thresholdExceeds = {false, false, false}; // Array to track if voltage exceeds threshold
long[] startTimes = new long[3]; // Array to store start times of threshold exceedance
long lastLegMovementTime = 0; // Last time a leg movement was counted
int legMovementCount = 0; // Counter for leg movements

long lastELMTime = 0; // Last time an ELM was counted
int ELMCount = 0; // Counter for ELMs
int PLMCount = 0; // Counter for PLMs

int dataIndex = 0; // Data index
int maxDataPoints = 400; // Maximum number of data points
float[] timeStamps = new float[maxDataPoints]; // Array to store timestamps
float[][] voltageHistory = new float[3][maxDataPoints]; // Array to store voltage history
color[] colors = {color(255, 0, 0), color(0, 255, 0), color(0, 0, 255)}; // Colors for plotting

void setup() {
  size(800, 800); // Window size
  String portName = Serial.list()[0]; // Choose the first available port
  myPort = new Serial(this, portName, 9600); // Initialize serial communication
}

void draw() {
  background(255); // Set background color to white
  
  // Draw axes
  stroke(0); // Set color to black
  strokeWeight(1);
  
  // X-axis
  line(100, height - 100, width - 100, height - 100);
  // Y-axis
  line(100, height - 100, 100, 100);
  
  // Draw X-axis ticks and labels
  float xTickInterval = (width - 200) / 5.0; // X-axis tick interval
  for (int i = 0; i <= 5; i++) {
    float x = 100 + i * xTickInterval;
    stroke(0);
    line(x, height - 95, x, height - 105); // X-axis tick
    fill(0);
    textAlign(CENTER);
    text(nf((dataIndex - (5 - i)) * 1000 / 60, 1, 0) + "s", x, height - 80); // X-axis label
  }
  
  // Draw Y-axis ticks and labels
  float yMax = 5.0; // Y-axis max value
  float yTickInterval = 0.1; // Y-axis tick interval
  int numYTicks = int((yMax / yTickInterval)) + 1; // Number of Y-axis ticks
  for (int i = 0; i < numYTicks; i++) {
    float y = height - 100 - i * (height - 200) / (yMax / yTickInterval);
    stroke(0);
    line(95, y, 105, y); // Y-axis tick
    fill(0);
    textAlign(RIGHT);
    text(nf(i * yTickInterval, 1, 1), 80, y + 5); // Y-axis label
  }
  
  // Read serial data
  if (myPort.available() > 0) {
    String dataString = myPort.readStringUntil('\n'); // Read a line of data
    if (dataString != null) {
      String[] data = split(dataString, ','); // Split data by comma
      if (data.length == 3) {
        for (int i = 0; i < 3; i++) {
          voltages[i] = float(data[i]); // Parse voltage values
        }
        
        // Update historical data
        timeStamps[dataIndex] = millis() / 1000.0; // Current time (seconds)
        for (int i = 0; i < 3; i++) {
          voltageHistory[i][dataIndex] = voltages[i];
        }
        
        // Update data index
        dataIndex = (dataIndex + 1) % maxDataPoints;
        
        // Check for leg movement based on threshold criteria
        checkLegMovement();
      }
    }
  }

  // Draw voltage curves
  for (int i = 0; i < 3; i++) {
    stroke(colors[i]); // Set color
    noFill();
    beginShape();
    for (int j = 0; j < maxDataPoints; j++) {
      int index = (dataIndex + j) % maxDataPoints;
      float x = 100 + j * (width - 200) / (float)(maxDataPoints - 1);
      float y = height - 100 - voltageHistory[i][index] * (height - 200) / 5.0;
      vertex(x, y);
    }
    endShape();
  }

  // Draw legend
  noStroke();
  String[] labels = {"Dorsum", "Ankle", "Tibialis"}; // Legend labels
  for (int i = 0; i < 3; i++) {
    fill(colors[i]);
    rect(width - 200, 50 + i * 30, 20, 20); // Draw legend box
    fill(0);
    textAlign(LEFT);
    text(labels[i], width - 170, 65 + i * 30); // Label text
  }

  // Display leg movement count
  fill(0);
  textAlign(CENTER);
  textSize(16);
  text("Leg Movement: " + legMovementCount, width / 2, height - 30);

  // Display ELM count
  text("ELM Count: " + ELMCount, width / 2, height - 50); // 显示ELM计数

  // Display PLM count and current time if ELMCount >= 4
  if (ELMCount >= 4) {
    String dateTime = year() + nf(month(), 2) + nf(day(), 2) + " " + nf(hour(), 2) + ":" + nf(minute(), 2) + ":" + nf(second(), 2);
    text(dateTime + " PLM: " + PLMCount, width / 2, height - 70); // 显示PLM计数和当前时间
  }
}

// Function to check leg movement
void checkLegMovement() {
  long currentTime = millis();

  // Check each sensor
  for (int i = 0; i < 3; i++) {
    if (voltages[i] >= 0.1875) {
      if (!thresholdExceeds[i]) {
        startTimes[i] = currentTime; // Start time of threshold exceedance
        thresholdExceeds[i] = true;
      }
    } else {
      thresholdExceeds[i] = false;
      startTimes[i] = 0;
    }
  }

  // Check if all three sensors exceed the threshold for 0.5 to 10 seconds
  boolean allSensorsExceed = true;
  for (int i = 0; i < 3; i++) {
    if (startTimes[i] == 0 || currentTime - startTimes[i] < 500 || currentTime - startTimes[i] > 10000) {
      allSensorsExceed = false;
      break;
    }
  }

  if (allSensorsExceed) {
    if (currentTime - lastLegMovementTime >= 1000) { // Avoid counting multiple times per second
      // Calculate inter-movement interval
      long interMovementInterval = currentTime - lastELMTime;

      // Check if the interval is within the specified range
      if (interMovementInterval >= 5000 && interMovementInterval <= 90000) {
        ELMCount++;
        lastELMTime = currentTime; // Update last ELM time

        // Print the current date and time with ELM count
        String dateTime = year() + nf(month(), 2) + nf(day(), 2) + " " + nf(hour(), 2) + ":" + nf(minute(), 2) + ":" + nf(second(), 2);
        println(dateTime + " ELM: " + ELMCount);
      }

      // Increment PLM count if ELM count is 4 or more
      if (ELMCount >= 4) {
        PLMCount++;
        String dateTime = year() + nf(month(), 2) + nf(day(), 2) + " " + nf(hour(), 2) + ":" + nf(minute(), 2) + ":" + nf(second(), 2);
        println(dateTime + " PLM Count Incremented: " + PLMCount); // Debug message to indicate PLM count increment
        // Reset ELM count or keep as desired
        ELMCount = 0; // Reset ELM count after PLM count increment
      }

      legMovementCount++;
      lastLegMovementTime = currentTime;

      // Print the current date and time with leg movement count
      String dateTime = year() + nf(month(), 2) + nf(day(), 2) + " " + nf(hour(), 2) + ":" + nf(minute(), 2) + ":" + nf(second(), 2);
      println(dateTime + " Leg Movement Count: " + legMovementCount);
    }
  }
}
